package com.sh4.controller.wx;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sh4.service.impl.CoreServiceImpl;
import com.sh4.util.JackJsonUtils;
import com.sh4.util.Sh4Utils;
import com.sh4.util.wechatUtils.Core;
import com.sh4.util.wechatUtils.MessageUtil;
import com.sh4.wxservice.WeChatRequest;
import com.sh4.wxservice.message.resp.TextMessage;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value="wx")
public class authorizeController {
	
	@Autowired
	CoreServiceImpl coreServiceImpl;
	
	static String rootServerUrl = "http://www.xgfsgc.com/weixin/leakpoint/";
	static String replaceServerUrl = "http://www.xgfsgc.com/weixin/leakpoint/#/";

	@ResponseBody
	@RequestMapping(value = "authorize")
	public void authorize(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String state = request.getParameter("state");
		String code = request.getParameter("code");
		// String companyCode = request.getParameter("companyCode");
		String url = request.getParameter("url");
		System.out.println("url="+url);
		if (code != null) {
			System.out.println("code="+code+"|||||||"+"state="+state);
			JSONObject rs = Core.getOauthAccessToken(code,Sh4Utils.getWxAppId(),Sh4Utils.getAppSecret());// 根据code换取
			String openid = rs.getString("openid");
			System.out.println("openid="+openid);
			String parameter = "?code=" + code + "&state=" + state + "&openId="
					+ openid;
			url = url.replace(rootServerUrl, replaceServerUrl);
			response.sendRedirect(url + parameter);
		} else {
			response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="
					+ Sh4Utils.getWxAppId()
					+ "&redirect_uri="
					+ Sh4Utils.urlEncode(Sh4Utils.getRootUrl() + "/wx/authorize?url=" + rootServerUrl + url)
					+ "&response_type=code&scope=snsapi_userinfo&state="
					+ state + "&connect_redirect=1#wechat_redirect");
		}
		
	}
	
	/**
     * 服务号 入口
     * @param response
     * @param request
     */
    @RequestMapping(value = "/passageway", method = {RequestMethod.POST,RequestMethod.GET})
    public void serve(HttpServletResponse response, HttpServletRequest request)  throws IOException {
        String method = request.getMethod();
        PrintWriter out = response.getWriter();
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        switch (method){
            case "GET":
            	 // 公司ID
//                String tenantId = request.getParameter("companyCode");
                
                // 微信加密签名
                String signature = request.getParameter("signature");
                // 时间戳
                String timestamp = request.getParameter("timestamp");
                // 随机数
                String nonce = request.getParameter("nonce");
                // 随机字符串
                String echostr = request.getParameter("echostr");

                // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
                if (Sh4Utils.checkSignature(signature,Sh4Utils.getToken(), timestamp, nonce)) {
                    out.print(echostr);
                    System.out.println("======================="+"配置成功！");
                }
                out.close();
                out = null;

                break;
            case "POST":
                
                // 调用核心业务类接收消息、处理消息
                String respMessage = processRequest(request);
                respMessage=new String(respMessage.getBytes("UTF-8"), "iso88591");
                // 响应消息
                out.print(respMessage);
                out.close();
                break;
        }
    }
    
    @RequestMapping(value = "/updateMenu" , method = RequestMethod.POST)
    @ResponseBody
	public Map<String, Object> save(@RequestBody JSONObject params) {
		
		Map<String, Object> result = new HashMap<String,Object>();
		int status = 200;
		String msg = "提交成功";
		try {
			
			String accessToken = Sh4Utils.getAccess_token();
			System.out.println("accessToken = " + accessToken);
			System.out.println("更新服务号菜单返回：" + Core.updateMenu(params.toString(), accessToken));
			
		} catch (Exception e) {
			status = 300;
			msg = "内部错误";
		}
		result.put("status", status); 
		result.put("msg", msg);
		
		return result;
		
	}
    
    /**
	 * 处理微信发来的请求  分发类型 处理不同的类型的微信 通知
	 *
	 * @param request
	 * @return
	 */
	public  String processRequest(HttpServletRequest request) {
		String respMessage = "";

		try {
			// 默认返回的文本消息内容
			String respContent = "";
			String companyCode = "xgfs";//request.getParameter("companyCode"); // 公司ID
			System.out.println("=======================" + companyCode + "服务号！");

			/************************
			 * xml请求解析 并 转 对象 start
			 *****************************/
			// map ==> WeChatRequest 对象
			WeChatRequest wr = JackJsonUtils.fromJson(JSONObject.fromObject(MessageUtil.parseXml(request)).toString(),
					WeChatRequest.class);
			System.out.println("JSON：==》 "+JSONObject.fromObject(wr).toString());
			String accesstoken = Sh4Utils.getAccess_token();
			wr.setCompanyCode(companyCode);
			wr.setCompanyToken(accesstoken);
			
			/************************ xml请求解析end *****************************/

			/*************************
			 * 回复文本消息 satrt
			 *****************************/
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(wr.getFromUserName());
			textMessage.setFromUserName(wr.getToUserName());
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);

			String msgType = wr.getMsgType();// 消息类型
			switch (msgType) {
			     case MessageUtil.REQ_MESSAGE_TYPE_EVENT: // 推送
//				      CoreServiceImpl coreServiceImpl = new CoreServiceImpl();
				     /**
				       * 记录该扫描事件
				       */
				       String EventKey = wr.getEventKey();
				    /**
				      * 根据不同事件 进行相应业务操作
				      */
				     switch (wr.getEvent()) {// 事件类型
				            case MessageUtil.EVENT_TYPE_SUBSCRIBE: // subscribe(订阅)
				                	if (StringUtils.hasText(EventKey)) {              // 扫码关注事件
						                respContent = coreServiceImpl.subscribeScan(wr);
				                	} else {                                          // 普通关注事件
						                respContent = coreServiceImpl.subscribe(wr);
					                }
//					                    textMessage.setContent(respContent);
//					                    respMessage = MessageUtil.textMessageToXml(textMessage);
					                break;
				           case MessageUtil.EVENT_TYPE_ALREADY_SUBSCRIBE:             // 用户已关注时的事件
				                     	respContent = coreServiceImpl.subscribeOldScan(wr);
			                		break;
			               case MessageUtil.EVENT_TYPE_UNSUBSCRIBE:                   // unsubscribe(取消订阅)
			            	   coreServiceImpl.unSubscribe(wr.getFromUserName());
					                break;

				           case MessageUtil.EVENT_TYPE_CLICK:                          // CLICK(自定义菜单点击事件)
			                    		// 事件KEY值，与自定义菜单接口中KEY值对应
					                    System.out.println(wr.getEventKey());
					                    respContent = wr.getEventKey();
					                break;
				           case MessageUtil.EVENT_TYPE_REDIRECT:                       // 点击菜单跳转链接时的事件推送
				                    	System.out.println(wr.getEventKey());
					                break;

				           case MessageUtil.REQ_MESSAGE_TYPE_LOCATION:                 // 地理位置
					                    System.out.println("纬度" + wr.getLatitude() + "经度" + wr.getLongitude() + "精度" + wr.getPrecision());
					                break;
				           case MessageUtil.EVENT_TYPE_LOCATION: // 发送地理位置
				        	  
			                break;
				           }
				          break;
			case MessageUtil.REQ_MESSAGE_TYPE_TEXT:
				    respContent="感谢您对我们的支持！[微笑]";
				         break;
		     	case MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
		     		respContent="图片已经接收！";
				         break;
			    case MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
			    	respContent="地理位置已获取！";
				         break;
			    case MessageUtil.REQ_MESSAGE_TYPE_LINK:
			    	respContent="链接已访问！";
				        break;
			    case MessageUtil.REQ_MESSAGE_TYPE_VOICE:
			    	respContent="音频已接收！";
				        break;
			   }
			textMessage.setContent(respContent);
			respMessage = MessageUtil.textMessageToXml(textMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}
}
